package com.bysj.agent.service.impl;

import com.bysj.agent.config.ImageAnalysisModel;
import com.bysj.agent.service.ImageAnalysisService;
import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.openai.OpenAiChatModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Base64;

@Service
@Slf4j
public class ImageAnalysisServiceImpl implements ImageAnalysisService {

    private final OpenAiChatModel imageAnalysisModel;

    // 通过构造器注入 imageAnalysisModel
    @Autowired
    public ImageAnalysisServiceImpl() {
        this.imageAnalysisModel = OpenAiChatModel.builder()
                .apiKey("sk-a691c2b981cc401e99536eeca9ba7af4")
                .modelName("qwen-vl-max")  // 设置使用的模型名称
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();
    }
    @Override
    public String analysisImage(MultipartFile image) {
        if (image == null){
            log.error("图片为空");
            return "图片为空";
        }
        String name = image.getName();
        try {
            InputStream inputStream = image.getInputStream();
            byte[] byteArray = IOUtils.toByteArray(inputStream);
            inputStream.close();
            String encodeToString = Base64.getEncoder().encodeToString(byteArray);
            UserMessage userMessage = UserMessage.from(TextContent.from("详细的描述图片，不要使用md格式,用中文回答"),
                                                        ImageContent.from(encodeToString, name));

            ChatResponse response = imageAnalysisModel.chat(userMessage);
            System.out.println(response.aiMessage().text());
            return response.aiMessage().text();
        } catch (Exception e) {
            log.error("图片分析失败", e);
            return "图片分析失败";
        }
    }
}
